/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <string>
#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>

#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
        if (argc < 2) {
                std::cerr << "ERROR, no port provided" << std::endl;
                return 1;
        }
        //creates new socket IPv4 TCP and stores descriptor in sockfd
        int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd < 0) {
                std::cerr << "ERROR opening socket" << std::endl;
                return 1;
        }

        //Creates and initializes sock_addr_in structure.
        sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(sockaddr_in));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_addr.s_addr = INADDR_ANY;
        // htons converts 16bit integer to network byte order.
        int portno = atoi(argv[1]);
        serv_addr.sin_port = htons(portno);

        if(bind(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
                std::cerr << "Can't bind socket: errno " << errno << std::endl;
                return 1;
        }
        // Start listening for incoming connections, 5 is size of backlog queue.
//	while(1){
//	listen(sockfd, 5);

//	sockaddr_in cli_addr;
//	socklen_t clilen = sizeof(cli_addr);
//	int newsockfd = accept(sockfd, (sockaddr*)&cli_addr, &clilen);
/*        if (newsockfd < 0) {
                std::cerr << "ERROR on accept" << std::endl;
                return 1;
        }
*/
//	std::cout << "New Port no: " << cli_addr.sin_port << std::endl;

//	char buffer[256];
	int16_t value = 33;
//	memset(buffer, 0, sizeof(buffer));
	memset(&value, 0, sizeof(value));
//	int n = read(newsockfd, buffer, 255);
	for(int i = 0; i < 100; i++){
	int n = read(sockfd, &value, sizeof(value));
//	std::cout <<"Before ntohs: "<< value << std::endl;
        if (n < 0) {
                std::cerr << "Error reading from socket" << std::endl;
                return 1;
        }
	value = ntohs(value);
        std::cout << n << " bytes received" << std::endl;
//	std::cout << "Message received: " << buffer << std::endl;
	std::cout << "Message received: " << value << std::endl;
	}//for
/*        const char* c = "Message delivered";
//	n = write(sockfd, c, strlen(c));
        if (n < 0) {
                std::cerr << "Error writing to socket" << std::endl;
                return 1;
        }
*/	
//	}
        return 0; 
}
